package com.iflytek.ssm.dao;

import com.iflytek.ssm.entity.Students;
import com.iflytek.ssm.utils.DBUtil;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class StudentDao {

    /**
     * 根据id获取学生信息
     *
     * @param id 主键
     * @return 学生对象
     * @throws SQLException
     */
    public Students getStudentById(Integer id) throws SQLException {

        // 1、获取连接
        Connection con = DBUtil.getConnection();
        ResultSet rs = null;
        PreparedStatement ps = null;
        // 2、准备sql：参数用?占位符去替换
        String sql = "SELECT * FROM `student` WHERE id=?";
        try {
            /// 3、参数预处理
            ps = con.prepareStatement(sql);
            ps.setInt(1, id);

            // 4、执行sql 获取数据库返回的结果集
            rs = ps.executeQuery();
            if (rs.next()) {
                Students stu = new Students();
                stu.setId(rs.getInt("id"));
                stu.setName(rs.getString("name"));
                stu.setNo(rs.getString("no"));
                // ...
                return stu;
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            // 5、关闭链接
            DBUtil.close(rs);
            DBUtil.close(ps);
            DBUtil.close(con);
        }
        return null;
    }

}
